<?php
	class UsersRolesController extends Controller
	{
		public $page_title = LANG_USERS_ROLES;
		public $layout = 'main';
		public $module = 'administration';
		public $helpers = array ('html', 'htmlx', 'toolbars', 'grids|index');
		public $name = 'usersroles';
		
		function edit($user_id)
		{
			$this->data[roles] = $this->controller_model->GetByUserId($user_id);
			$this->data[user_id] = $user_id;
			$this->data[user] = $this->GetModelObject('users')->Get($user_id);
			if (!empty($this->request->post))
			{
				$post = $this->request->post;
				if ($this->SaveUsersRoles($post))
				{
					$this->Redirect('users/edit/'.$user_id);
				}
				else
				{
					$this->controller_model->validation_errors = $usersRolesModel->validation_errors;
				}
			}
		}
		
		function view($user_id)
		{
			$this->data[roles] = $this->controller_model->GetByUserId($user_id);
			$this->data[user_id] = $user_id;
			$this->data[user] = $this->GetModelObject('users')->Get($user_id);
		}
		
		private function SaveUsersRoles($post)
		{
			$result = true;
			$usersRolesModel =  $this->GetModelObject('usersRoles');
			$roles = '';
			$i = 0;
			foreach ($post[userRole] as $key=>$value)
			{
				if ($i==0)
				{
					$roles = $key;
				}
				else 
				{
					$roles = $roles . ','.$key;
				}
				$i++;
			}
			if($usersRolesModel->AddUserRole($post[user_id], $roles) == 0)
			{
				$result = false;
				break;
			}
			return $result;
		}
	}
?>